﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonNet48.ConfigUtils
{
    /// <summary>
    /// Json配置文件帮助类
    /// </summary>
    public class JsonConfigHelper
    {
        private static Dictionary<string, IConfigurationRoot> _Cfgs = new Dictionary<string, IConfigurationRoot>();
        /// <summary>
        /// 读取配置文件配置项
        /// </summary>
        /// <typeparam name="T">配置项类型</typeparam>
        /// <param name="key"></param>
        /// <param name="defaultValue">默认返回值。如果未找到配项返回该值。</param>
        /// <param name="fPath">配置文件路径</param>
        /// <returns></returns>
        public static T GetSettings<T>(string key, T defaultValue, string fPath)
        {
            IConfigurationRoot configuration = GetConfiguration(fPath);
            if (configuration == null) return defaultValue;
            string configValue = configuration.GetSection(key).Value;
            var result = string.IsNullOrEmpty(configValue) ? defaultValue : (T)Convert.ChangeType(configValue, typeof(T));
            return result;
        }

        /// <summary>
        /// 获取配置文件访问对象
        /// </summary>
        /// <param name="fPath"></param>
        /// <returns></returns>
        private static IConfigurationRoot GetConfiguration(string fPath)
        {
            IConfigurationRoot configuration = null;
            if (_Cfgs.ContainsKey(fPath))
            {
                configuration = _Cfgs[fPath];
            }
            else
            {
                IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile(fPath, true, true);
                configuration = builder.Build();
                _Cfgs.Add(fPath, configuration);
            }
            return configuration;
        }


    }
}
